<?php

parse_str(file_get_contents('php://input'), $postbody);
$port = $postbody["p"];
if($port){
    if(intval($port) < 23 || intval($port) > 65534){
        die("Invalid port.");
    }
}else{
    die("No port provided.");
}


$servername = $postbody["sn"];
if($servername){
    if(strlen($servername) == 0 || strlen($servername) > 30){
        die("Invalid server name.");
    }
}else{
    die("No server name provided.");
}

$map = $postbody["m"];
if($map){
    if(strlen($map) == 0 || strlen($map) > 30){
        die("Invalid map name.");
    }
}else{
    die("No map name provided.");
}

$numplayers = $postbody["np"];
if (intval($numplayers) < 0 || intval($numplayers) > 254) {
    die("Invalid number of players.");
}


$maxplayers = $postbody["mp"];
if (intval($maxplayers) < 0 || intval($maxplayers) > 254) {
    die("Invalid number of players.");
}

$url = $postbody["u"];
if($url){
    if(strlen($url) > 100){
        die("Url too long.");
    }
}

$locked = $postbody["l"];
if($locked){
    if(intval($locked) != 0 && intval($locked) != 1){
        die("Invalid lock information.");
    }
}else{
    $locked = 0;
}

$version = $postbody["v"];
if($version){
    if(strlen($version) == 0 || strlen($version) > 10){
        die("Invalid version number.");
    }
}else{
    die("No version number proivided.");
}

$mysqli = new mysqli("jmpmain.com", "jmpmain_tracker", "_", "jmpmain_servertracker");
if(mysqli_connect_errno()){
  die("Could not resolve mysql connection.");
}

$ip = $_SERVER['REMOTE_ADDR'];

$mysqli->query("delete from current where ip='" . $ip . "' and port='". $port ."';");
$result = $mysqli->query("insert into current(ip, port, servername, mapname, numplayers, maxplayers, url, locked, version)" .
        "values('" . $ip . "', ". $port . ", '" . $servername . "', '" . $map .
        "', " . $numplayers . ", " . $maxplayers . ", '". $url . "', " . $locked . ", '" .  $version . "');");

$mysqli->query("insert into servershist(ip, port, servername, mapname, numplayers, maxplayers, url, locked, version)" .
        "values('" . $ip . "', ". $port . ", '" . $servername . "', '" . $map .
        "', " . $numplayers . ", " . $maxplayers . ", '". $url . "', " . $locked . ", '" .  $version . "');");

if($result == 1){
    echo "1";
}else{
    echo "0";
}
$mysqli->close();
?>